<template>
    <el-dialog v-model="store.state.HomeModules.dialogFormVisible" title="编辑商品" width="30%" @close="resetForm">
        <el-form :model="form" ref="ruleFormRef" :rules="rules" status-icon>
            <el-form-item label="藏品名称" prop="shopName">
                <el-input v-model="form.shopName" />
            </el-form-item>
            <el-form-item label="藏品价格" prop="shopPrice" :rules="[
                { required: true, message: '请输入藏品价格' },
                { type: 'number', message: '请输入数字值' },
            ]">
                <el-input v-model.number="form.shopPrice" />
            </el-form-item>
            <el-form-item label="图片" prop="shopImg">
                <el-upload action="#" :limit="1" list-type="picture-card" :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove" :on-exceed="handleExceed" :before-upload="handleUpload"
                    :http-request="uploadAction">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="updateDialog(ruleFormRef)">
                    修改
                </el-button>
                <el-button @click="closeDialog()">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useStore } from 'vuex';
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadRequestOptions, UploadRawFile } from 'element-plus'
import { updateShopList } from "../api/api";

let store = useStore()
const form = reactive({
    shopName: '',
    shopPrice: '',
    shopImg: '',
})

const rules = reactive<FormRules>({
    shopName: [
        { required: true, message: '请输入分类', trigger: 'blur' }
    ],
    shopPrice: [
        { required: true, message: '请输入价格' },
        { type: 'number', message: '请输入数字值' },
    ],
})

const dialogImageUrl = ref<string | undefined>('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}

const handleExceed: UploadProps['onExceed'] = (files) => {
    ElMessage.warning(
        `允许上传图片的最大数量为 ${files.length} 张`
    )
}

const handleUpload = (rawFile: UploadRawFile) => {
    const type = ['image/jpeg', 'image/jpg', 'image/png']
    if (type.indexOf(rawFile.type) === -1) {
        ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}

const uploadAction = (data: UploadRequestOptions) => {
    let reader = new FileReader() // 创建文件读取对象
    let file = data.file
    reader.readAsDataURL(file) // 文件读取转换为base64类型
    reader.onloadend = function (e: any | null) {
        // console.log(e.target.result);
        form.shopImg = e.target.result
    }
    let param = new FormData();
    param.append('file', data.file);
}

// 修改商品
const updateDialog = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return
    ruleForm.validate(async (valid: any, fields: any) => {
        let data = {
            shopImg: form.shopImg,
            shopName: form.shopName,
            shopPrice: form.shopPrice
        }
        let id = store.state.HomeModules.uplistData._id
        if (valid) {
            // 发送请求
            console.log('submit!')
            await updateShopList(id, data)
            // if (res) {
            //     ElMessage({
            //         message: '修改成功',
            //         type: 'success',
            //     })
            // }
            store.commit("DIALOG")
        } else {
            console.log('error submit!', fields)
            return false
        }
    })
}

// 关闭弹窗
const closeDialog = () => {
    store.commit("DIALOG")
}

// 重置表单
const ruleFormRef = ref<FormInstance>()
const resetForm = (ruleForm: FormInstance | undefined) => {
    if (!ruleForm) return;
    ruleForm.resetFields();
}
</script>

<style scoped>
.el-dialog .el-form {
    margin: 0 40px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>